import { useState } from "react";
import { useMount } from "ahooks";

import ApiWork from "@/api/work";
import request from "@/utils/request";

import { ConstructionPlanFormItem } from "@/types/work";

/**
 * 紧前工序：
 * 后项工序的 prePlanId 指向前置 工序的constructionPlanId
 *
 * 当删除A项后，遍历所有项：
 * 1. 如果A项prePlanId存在值，关联A项constructionPlanId的全部项的prePlanId全部替换为A的prePlanId
 * 2. 如果A项没有，则为0
 */

const planItemKeys = [
  ["isSend"], // ?
  ["isSendNew"], // ?
  // "constructionPlanId",

  // ["constructionId"], // 施工ID
  ["constructionPlanTemplateId"], // constructionPlanTemplateId
  ["constructionProjectName", "constructionPlanName"], // 施工项目名称
  // ["intentCustomerId"], // 意向客户ID
  // ["customerName"], // 客户名称
  // ["customerNo"], // 客户编号
  ["period"], // 周期
  // ["planStartDate"], // 计划开始日期
  // ["planFinishDate"], // 计划完成日期
  ["sortId"], // 排序ID
  ["isMustComplete"], // 必做
  ["internalTest"], // 内验
  ["notIncludedPeriod"], // 不计入周期
  ["workerType"], // 工种
  ["materialPlanTemplate"],
  ["executePostNames"],
  ["executePostIds"],
  ["prePlanId"]
];

/**
 * 根据模板生成拟定计划列表
 */
function generateConstructionPlanListByTemp(list: any, defaultPObj: any) {
  return list.map((item) => {
    const obj = planItemKeys.reduce(
      (obj, [key1, key2 = key1]) => {
        obj[key1] = item[key2];
        return obj;
      },
      { ...defaultPObj, _id: +new Date() } as Record<string, any>
    );
    return obj as ConstructionPlanFormItem;
  });
}

export default (intentCustomerId) => {
  const [data, setData] = useState<any>();

  const mergeData = async () => {
    // @ts-expect-error
    const { contractInfo } = await request({
      url: ApiWork.getContractInfo,
      data: { intentCustomerId },
    });

    // @ts-expect-error
    const { list } = await request({
      url: ApiWork.getConstructionPlanTemplateListByCid,
      data: { intentCustomerId },
    });

    // 施工模板详情
    // @ts-expect-error
    const { constructionTemplateDetail: templateDetail } = await request({
      url: ApiWork.getConstructionTemplateDetail,
      data: { constructionTemplateId: list[0]["constructionTemplateId"] },
    });

    const planStartDate = contractInfo.plandBeginDate!.split(" ")[0];

    // 2. 初始化表单PlanList数据
    const defaultObj = {
      intentCustomerId,
      customerNo: contractInfo!.customerNo,
      customerName: contractInfo!.customerName,
    };

    const newData = {
      planStartDate,
      realEndDate: "",
      realStartDate: planStartDate,
      contractExpectDate: planStartDate,

      intentCustomerId,
      customerNo: contractInfo!.customerNo,
      customerName: contractInfo!.customerName,
      period: contractInfo.contractDuration,

      // 模板code
      constructionCode: templateDetail.TemplateCode,
      // 施工名称
      constructionName: templateDetail.TemplateName,
      // 施工模板ID
      constructionTemplateId: templateDetail.constructionTemplateId,

      formConstructionPlanList: generateConstructionPlanListByTemp(
        list,
        defaultObj
      ),
    };

    setData(newData);
  };

  const initial = async () => {
    request(
      {
        url: ApiWork.getDraftConstructionPlan,
        data: { intentCustomerId },
        method: "POST",
      },
      { showErrorToast: false }
    ).then(
      (res) => setData(res),
      () => mergeData()
    );
  };

  useMount(() => initial());

  return data;
};
